<?php
// 这个管入口文件index.php，在home里面。
namespace Home\Controller;

use Component\Home2Controller;

class IndexController extends Home2Controller
{
    function index(){
        $this->display();
    }

    function index2(){
        $this->display();
    }

    //头部页面
    function head()
    {
        if (!empty($_POST["ok"])) {
            if(!empty($_POST["word"])&&trim($_POST["word"])!=""){
                session('word', trim($_POST["word"]));
            }else{
                session('word',null);
            }
            $this->redirect("res/res");
            //不要加一开始的/，不然会变成从index。php开始的绝对路径
        }else{
            $this->display();
        }

    }

    //左边页面
    function left(){
        $sql = "select * from sw_style";
        $sinfo = D()->query($sql);
        //var_dump($sinfo);
        $this -> assign('sinfo',$sinfo);
        $this -> display();
    }

    //右边页面
    function right()
    {
        $messages = D("Message");
        //1. 获得当前记录总条数
        $total = $messages-> where("message_tag like '%".$_GET["style"]."%'")->count();
        //echo "total=".$total;
        $per = 10;//一页显示几行
        //2. 实例化分页类对象
        $page = new \Component\Page($total, $per); //autoload
        //3. 拼装sql语句获得每页信息
        $sql = "select * from sw_message " ;
        //if(!empty($_GET["style"])){
            $sql=$sql."where message_tag like '%".$_GET["style"]."%' order by message_time desc ";
        //}
        $sql=$sql. $page->limit;
        //echo $sql;
        $info = $messages->query($sql);
        //4. 获得页码列表
        $pagelist = $page->fpage();

        $comment=D("Comment");
        foreach($info as $k => $v){
            $c=$comment->where("message_id='".$v["message_id"]."'")->count();
            $info[$k]["comment_count"]=$c;
        }
        //var_dump($info);

        $this->assign('info', $info);
        $this->assign('pagelist', $pagelist);//跳转导航列表
        //echo date("y-m-d H:i:s",time());
        $this->display();
    }

    //他人主页
    function other($user_id)
    {
        //查询该用户信息
        $user = D("User");
        $info = $user->find($user_id); //一维数组
        $this->assign('info', $info);

        //查询自己是否关注过该用户
        $follow=D("Follow");
        $rst=$follow->where("user_id=".$user_id." and follower_id=".$_SESSION['user_id'])->select();
        if(!empty($rst)){
            $this->assign('follow','del_follow');
            $this->assign('fol','取消关注');
        }else{
            $this->assign('follow','add_follow');
            $this->assign('fol','关注');
        }

        //查询该用户发布的分享条目
        $message=D("Message");
        $total=$message->where("user_id='".$user_id."'")->count();
        $per = 10;//一页显示几行
        //2. 实例化分页类对象
        $page = new \Component\Page($total, $per); //autoload
        //3. 拼装sql语句获得每页信息
        $sql = "select * from sw_message " ;
        $sql=$sql."where user_id = '".$user_id."' order by message_time desc ";
        $sql=$sql. $page->limit;
        $minfo = $message->query($sql);
        //4. 获得页码列表
        $pagelist = $page->fpage();

        //查询评论条数
        $comment=D("Comment");
        foreach($minfo as $k => $v){
            $c=$comment->where("message_id='".$v["message_id"]."'")->count();
            $minfo[$k]["comment_count"]=$c;
        }

        $this->assign('minfo', $minfo);
        $this->assign('pagelist', $pagelist);
        $this->display();
    }

    //关注
    function add_follow($user_id){
        $follow =D("Follow");
        $follow->user_id=$user_id;
        $follow->follower_id=$_SESSION['user_id'];
        $rst=$follow->add();
        if ($rst) {
            $this->redirect("Home/my_followlist");
        }else {
            $this->assign("follow_info","关注失败,请稍后再试！");
            $this->redirect("Home/my_followlist");
        }
    }

    //取消关注
    function del_follow($user_id){
        $follow =D("Follow");
        $rst=$follow->where("user_id=".$user_id." and follower_id=".$_SESSION['user_id'])->delete();
        if ($rst) {
            $this->redirect("Home/my_followlist");
        }else {
            $this->assign("follow_info","取消关注失败,请稍后再试！");
            $this->redirect("Home/my_followlist");
        }
    }

    //我的关注页，显示自己和关注用户发布的分享条目
    function my_follow(){
        $addmessage = new \Model\MessageModel();

        //发布分享条目，必须上传图片，文字和标签可为空
        if(!empty($_POST)){//判断表单是否提交
            if (!empty($_FILES['message_img']['name'])) {
                $type = substr($_FILES['message_img']['name'],strrpos($_FILES['message_img']['name'],'.')+1);
                if($type=="jpg"||$type=="gif"||$type=="png") {
                    //echo "有文件";
                    $config = array(
                        'rootPath' => './public/',  //根目录
                        'savePath' => 'upload/', //保存路径
                    );
                    //附件被上传到路径：根目录/保存目录路径/创建日期目录
                    $upload = new \Think\Upload($config);
                    //uploadOne会返回已经上传的附件信息
                    $z = $upload->uploadOne($_FILES['message_img']);
                    if (!$z) {
                        //获得上传附件产生的错误信息
                        $this->assign("pic_info", "上传失败，请稍后重试!");
                    } else {
                        //拼装图片的路径名
                        $bigimg = $z['savepath'] . $z['savename'];
                        //$z[‘savepath’]值为：保存目录路径/创建日期目录，把图片的路径存入数据库
                        $_POST['message_big_img'] = $bigimg;

                        //把已经上传好的图片制作缩略图Image.class.php
                        $image = new \Think\Image();
                        //open();打开图像资源，通过路径名找到图像
                        $srcimg = $upload->rootPath . $bigimg;
                        $image->open($srcimg);
                        $image->thumb(150, 150);  //按照比例缩小
                        $smallimg = $z['savepath'] . "small_" . $z['savename'];
                        $image->save($upload->rootPath . $smallimg);
                        $_POST['message_small_img'] = $smallimg;
                    }
                    $_POST['username'] = $_SESSION['username'];
                    $_POST['user_id'] = $_SESSION['user_id'];
                    $_POST['message_time'] = time();//echo date("y-m-d",$time) //2010-08-29
                    if (!$addmessage->create()) {//只有全部验证通过$z才会为真
                        //验证失败,输出错误信息
                        show_bug($addmessage->getError()); //getError()方法返回验证失败的信息
                    } else {
                        //create()方法收集的数据也是把数据变为模型对象的属性
                        $addmessage->message_introduce = trim($_POST['message_introduce']);
                        $addmessage->message_tag = implode(',', $_POST['message_tag']);
                        $rst = $addmessage->add();
                        if ($rst) {
                            $this->assign("pic_info", "发布成功");
                        } else {
                            $this->assign("pic_info", "发布失败,请稍后重试!");
                        }
                    }
                }else{
                    $this->assign("pic_info", "格式错误,请注意图片格式!");
                }
            }else{
                $this->assign("pic_info","发布失败,请务必上传图片!");
            }
        }

        //查询我或我关注的用户发布的分享条目
        $follow=D("Follow");
        $info=$follow->where("follower_id=".$_SESSION["user_id"])->select();
        //var_dump($info);
        $str='';
        foreach($info as $v){
            $str=$str.$v["user_id"].",";
        }
//        $str = rtrim($str,',');
//        echo $str;

        $message=D("Message");
        $total = $message->where("user_id in (".$str.$_SESSION["user_id"].")")->count();
        $per = 10;
        $page = new \Component\Page($total, $per);
        $sql = "SELECT * FROM `sw_message` WHERE ( user_id in (".$str.$_SESSION["user_id"].")) order by message_time desc ";
        $sql=$sql.$page->limit;
        $minfo = $message->query($sql);
        $pagelist = $page->fpage();
        $comment=D("Comment");
        foreach($minfo as $k => $v){
            $c=$comment->where("message_id='".$v["message_id"]."'")->count();
            $minfo[$k]["comment_count"]=$c;
        }
        $this->assign('minfo', $minfo);
        $this->assign('pagelist', $pagelist);

        $this->display();
    }

    //评论页
    function comment($message_id){
        $message=D("Message");
        $minfo=$message->find($message_id);
        $this->assign("minfo",$minfo);

        $comment=D("Comment");
        $total = $comment->where("message_id=".$message_id)->count();
        $per = 10;
        $page = new \Component\Page($total, $per);
        $sql = "SELECT * FROM `sw_comment` WHERE ( message_id=".$message_id.") order by comment_time desc ";
        $sql=$sql.$page->limit;
        $cinfo = $message->query($sql);
        $pagelist = $page->fpage();
        $this->assign('cinfo', $cinfo);
        $this->assign('pagelist', $pagelist);

        if($minfo["user_id"]==$_SESSION["user_id"]){
            $this->assign("del","删除");
        }

        if(!empty($_POST['comment_inner'])&&trim($_POST['comment_inner'])!=""){

            $_POST['username'] = $_SESSION['username'];
            $_POST['user_id'] = $_SESSION['user_id'];
            $_POST['message_id'] = $message_id;
            $_POST['comment_time'] = time();//echo date("y-m-d",$time) //2010-08-29
            if(!$comment -> create()){//只有全部验证通过$z才会为真
                //验证失败,输出错误信息
                show_bug($comment->getError()); //getError()方法返回验证失败的信息
            } else {
                $rst = $comment->add();
                if ($rst) {
                    $this->redirect("/home/index/comment/message_id/$message_id");
                }
            }
        }
        $this->display();
    }

    //删除评论页
    function del_comment($comment_id,$message_id){
        $comment=D("Comment");
        $rst=$comment->delete($comment_id);
        if ($rst) {
            $this->redirect("/home/index/comment/message_id/$message_id");
        }
    }

    public function _empty()
    {
        echo "404 not found";
    }
}